<?php

namespace app\common\model;


use think\exception\HttpResponseException;
use think\Hook;
use think\Model;
use think\Request;
use think\Response;
use traits\model\SoftDelete;

class BaseModel extends Model
{
    use SoftDelete;

    protected $deleteTime = 'deletetime';

    protected $hidden = ['deletetime', 'updatetime', 'onlineswitch', 'weigh', 'recommendswitch', 'pivot'];

    //降序排序
    const WEIGH_DESC = 'weigh desc';

    public static function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        $course = new Course();
        $order = new CourseOrder();
        Hook::listen('course', $course);
        Hook::listen('order', $order);
    }

    /**
     * 时间
     */
    public function getCreateTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '';
    }

    /**
     * 图片
     */
    public function getImageAttr($value)
    {
        return $value ? request()->domain().$value : '';
    }

    /**
     * 头像
     */
//    public function getHeaderavatarAttr($value)
//    {
//        return $value ? request()->domain().$value : '';
//    }

    /**
     * 图片组
     */
    public function getImagesAttr($value)
    {
        if ($value) {
            $values = explode(',', $value);
            array_walk($values, function (&$val) {
                $val = request()->domain().$val;
            });
            return $values;
        } else {
            return [];
        }

    }

    /**
     * 前端显示
     */
    public static function whereOnline()
    {
        return ['onlineswitch' => ['>', 0]];
    }

    /**
     * 异常处理
     * @param Int $code     错误码
     * @param String $type  格式json
     */
    public static function error($code = 0, $msg = '', $type = 'json')
    {
        $result = [
            'code' => $code,
            'msg'  => $msg ?: (isset(config('errorMessage')[$code]) ? config('errorMessage')[$code] : ''),
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => [],
        ];
        $header = [];
        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }
    /**
     * 错误信息
     * @param int $code
     * @param null $data
     */
    public static function errorMsg($code = 0)
    {
        $msg = isset(config('errorMessage')[$code]) ? config('errorMessage')[$code] : '';
        self::error($code, $msg);
    }

}
